<template>
  <div class="app-container">
    <div class="font-w">{{ roomInfo.name }}</div>
    <div class="primary-section mt20 pv-12" style="width: 1000px;">
      <div class="font-w mb20">入住人基本信息</div>
      <el-form :model="form" :rules="formRules" ref="formRef" label-width="100px">
        <el-row>
          <el-col :span="4">
            <el-form-item label="电子合同">
              <el-switch
                v-model="form.isContract"
                inline-prompt
                :active-icon="Check"
                :inactive-icon="Close"
              />
            </el-form-item>
          </el-col>
          <el-col :span="10" v-if="form.isContract">
            <el-form-item label="选择模板" prop="templateId" required>
              <el-select v-model="form.templateId">
                <el-option label="系统模板" value="1"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- 需要做数组处理 -->
        <el-row :gutter="24" v-for="(item, index) in form.renterList" :key="index">
          <el-col :span="7">
            <el-form-item label="姓名" :prop="`renterList[${index}].name`" :rules="[{ required: true, message: '请输入姓名', trigger: 'blur'}]">
              <el-input v-model="form.renterList[index].name" placeholder="请输入姓名" style="width: 100%;"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item label="联系方式" :prop="`renterList[${index}].contacts`" :rules="[{ required: true, trigger: 'blur', message: '请输入手机号或邮箱' },
              { pattern: /^(1[3|4|5|6|7|8|9][0-9]\d{8}$)|(\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$)/, message: '请输入手机号或邮箱', trigger: 'blur' }]">
              <el-input v-model="form.renterList[index].contacts" placeholder="请输入手机号或邮箱" style="width: 100%;"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item label="证件号" :prop="`renterList[${index}].idCardNumber`">
              <el-input v-model="form.renterList[index].idCardNumber" placeholder="请输入身份证号" style="width: 100%;"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="3">
            <el-icon v-if="index !== 0" @click="handleRemoveRenter(index)"><CircleCloseFilled /></el-icon>
            <el-icon v-else><Wallet /></el-icon>
          </el-col>
        </el-row>
        <el-row :gutter="0">
          <el-col :span="12">
            <el-form-item label="入住周期" required>
              <el-row>
                <el-col :span="10">
                  <el-form-item prop="checkInStart">
                    <el-date-picker
                      v-model="form.checkInStart"
                      type="date"
                      placeholder="请选择开始时间"
                      style="width: 180px;"
                      @change="handleStartDateChange"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="2">
                  <span style="margin: 0 12px;">-</span>
                </el-col>
                <el-col :span="10">
                  <el-form-item prop="checkInEnd">
                    <el-date-picker
                      v-model="form.checkInEnd"
                      type="date"
                      placeholder="请选择结束时间"
                      style="width: 180px;"
                      @change="handleEndDateChange"
                    />
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-radio-group v-model="radio" @change="handleQuicklyDate" :disabled="!form.checkInStart">
              <el-radio-button :label="1" >1月</el-radio-button>
              <el-radio-button :label="3" >3月</el-radio-button>
              <el-radio-button :label="6" >6月</el-radio-button>
              <el-radio-button :label="12" >12月</el-radio-button>
            </el-radio-group>
          </el-col>
        </el-row>
        <el-row v-if="form.isContract">
          <el-col :span="8">
            <el-form-item label="租金" required>
              <el-row>
                <el-col :span="10">
                  <el-form-item prop="rentObject.rentCollectType" label-width="0">
                    <el-select v-model="form.rentObject.rentCollectType">
                      <el-option label="月租金" value="1"></el-option>
                      <el-option label="日租金" value="2"></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="14">
                  <el-form-item prop="rentObject.rent" label-width="0">
                    <el-input v-model="form.rentObject.rent" placeholder="请输入租金" @input="handleRentChange"></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="押金" prop="rentObject.deposit">
              <el-input v-model="form.rentObject.deposit" placeholder="请输入押金"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="居住人数" prop="people">
              <el-input-number v-model="form.people" placeholder="请输入居住人数"></el-input-number>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="form.isContract">
          <el-col :span="8">
            <el-form-item label="面积" prop="area">
              <el-input-number
                v-model="form.area"
                :controls="false"
                placeholder="请输入面积"
                style="text-align: left;"
              ></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="支付方式" prop="rentObject.rentType" required>
              <el-select v-model="form.rentObject.rentType" placeholder="请选择支付时间">
                <el-option label="每1月" value="1"></el-option>
                <el-option label="每2月" value="2"></el-option>
                <el-option label="每3月" value="3"></el-option>
                <el-option label="每4月" value="4"></el-option>
                <el-option label="每半年" value="5"></el-option>
                <el-option label="每一年" value="6"></el-option>
                <el-option label="一次性" value="7"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="用途" prop="useType" required>
              <el-select v-model="form.useType">
                <el-option label="居住" value="1"></el-option>
                <el-option label="商业" value="2"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item v-if="form.isContract">
          <el-space>
            <el-button :icon="CircleCheckFilled" @click="handleRoomInfo">房间物品</el-button>
            <el-button :icon="CircleCheckFilled" @click="handleOther">其他预定</el-button>
          </el-space>
        </el-form-item>
        <el-form-item>
          <el-space>
            <el-button :icon="CircleCheckFilled" @click="handleRentRange" v-if="!form.isContract">房租信息</el-button>
            <el-button :icon="CircleCheckFilled" @click="handleCohabitants">添加同住人</el-button>
            <el-button :icon="CircleCheckFilled" @click="handleAddBilling">添加记账</el-button>
            <el-button :icon="CircleCheckFilled" @click="handleReceivables">添加待收账单</el-button>
            <el-button :icon="CircleCheckFilled" @click="handleRemark">添加备注</el-button>
          </el-space>
        </el-form-item>
      </el-form>
      <div class="text-center">
        <el-button @click="handleContactsView">合同预览</el-button>
        <el-button @click="handleFinish">完成</el-button>
      </div>
    </div>
    <div>
      <div>账单详情</div>
      <el-table :data="billList" class="mt20" style="width: 100%">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="name" label="费用名称" />
        <el-table-column prop="money" label="金额" />
        <el-table-column prop="type" label="类型">
          <template #default="scope">
            {{ scope.row.type === 1 ? '待收账单' : '完成账单'}}
          </template>
        </el-table-column>
        <el-table-column prop="noticeDate" label="收付款日" :width="100" />
        <el-table-column label="操作" :width="120">
          <template #default="scope">
            <el-button link type="danger" @click="handleRemoveBilling(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <CohabitantsDl
      :visible="cohabitants.visible"
      :type="cohabitants.type"
      :form="cohabitants.form"
      @cancel="handleCohabitantsClose"
      @ok="handleCohabitantsOk"
     />
    <RentRangeDl
      :visible="rentRange.visible"
      :type="rentRange.type"
      :form="rentRange.form"
      @cancel="handleRentRangeClose"
      @ok="handleRentRangeOk"
    />
    <AddBillingDl
      :visible="addBilling.visible"
      :type="addBilling.type"
      :form="addBilling.form"
      @cancel="handleAddBillingClose"
      @ok="handleAddBillingOk"
    />
    <ReceivablesDl
      :visible="receivables.visible"
      :type="receivables.type"
      :form="receivables.form"
      @cancel="handleReceivablesClose"
      @ok="handleReceivablesOk"
    />
    <el-dialog title="备注" v-model="remarkVisible" width="520px" :fullscreen="mobile" :close-on-click-modal="false">
      <el-form :model="remarkForm" ref="remarkFormRef" label-width="0">
        <el-form-item prop="remark">
          <el-input type="textarea" v-model="remarkForm.remark" :rows="4" maxlength="150" placeholder="请填写备注信息" show-word-limit></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleRemarkCancel">取消</el-button>
          <el-button type="primary" @click="handleRemarkOk">
            确认
          </el-button>
        </span>
      </template>
    </el-dialog>
    <el-dialog title="其他约定" v-model="otherVisible" width="520px" :fullscreen="mobile" :close-on-click-modal="false">
      <el-form :model="otherForm" ref="otherFormRef" label-width="0">
        <el-form-item prop="other">
          <el-input type="textarea" v-model="otherForm.other" :rows="4" maxlength="150" placeholder="请输入其他约定" show-word-limit></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleOtherCancel">取消</el-button>
          <el-button type="primary" @click="handleOtherOk">
            确认
          </el-button>
        </span>
      </template>
    </el-dialog>
    <el-dialog title="房间物品" v-model="roomInfoVisible" width="520px" :fullscreen="mobile" :close-on-click-modal="false">
      <el-form :model="roomInfoForm" ref="roomInfoFormRef" label-width="0">
        <el-form-item prop="roomInfo">
          <el-input type="textarea" v-model="roomInfoForm.roomInfo" :rows="4" maxlength="150" placeholder="请输入房间物品" show-word-limit></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleRoomInfoCancel">取消</el-button>
          <el-button type="primary" @click="handleRoomInfoOk">
            确认
          </el-button>
        </span>
      </template>
    </el-dialog>
    <el-dialog title="办理入住" center v-model="successVisible" width="580px" :fullscreen="mobile" :close-on-click-modal="false">
      <div class="text-center">
        <el-icon size="60" color="var(--el-color-primary)"><SuccessFilled /></el-icon>
        <div class="mt20 fs-large font-w">办理入住成功</div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" @click="handleSuccessOk">
            完成
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
<script setup name="Checkin">
import {Check, CircleCheckFilled, Close} from '@element-plus/icons-vue'
import checkinApi from '@/api/room/checkin'
import CohabitantsDl from '../component/cohabitantsDl.vue'
import RentRangeDl from './rentRangeDl.vue'
import AddBillingDl from './addBillingDl.vue'
import ReceivablesDl from '../component/receivablesDl.vue'
import {parseTime} from '@/utils/ruoyi'
import useAppStore from '@/store/modules/app'
import useUserStore from '@/store/modules/user'
import {useRoute, useRouter} from 'vue-router'
import RoomApi from '@/api/room/room'

const { proxy } = getCurrentInstance()
const route = useRoute()
const router = useRouter()
const userStore = useUserStore()

onMounted(() => {
  form.value.roomId = route.query.roomId
  form.value.apartmentId = userStore.apartment.apartmentId
  getRoomInfo()
})

const radio = ref('')
const roomInfo = ref({})
const remarkVisible = ref(false)
const roomInfoVisible = ref(false)
const otherVisible = ref(false)
const successVisible = ref(false)
const billList = ref([])
const mobile = computed(() => useAppStore().device === 'mobile')
const data = reactive({
  form: {
    roomId: undefined,
    apartmentId: undefined,
    renterList: [{
      name: undefined,
      contacts: undefined,
      idCardNumber: undefined,
      mainFlag: 0
    }],
    checkInStart: parseTime(new Date(), '{y}-{m}-{d}'),
    checkInEnd: '',
    templateId: undefined,
    rentCollectType: undefined,
    useType: undefined,
    rentCollectCycle: undefined,
    remark: undefined,
    // 房间信息
    roomInfo: undefined,
    // 其他约定
    other: undefined,
    rentObject: {
      rentCollectType: '1',
      rent: undefined,
      deposit: undefined,
      rentType: '1'
    }
  },
  formRules: {
    checkInStart: [{ required: true, message: '请选择开始时间', trigger: 'blur' }],
    checkInEnd: [{ required: true, message: '请选择结束时间', trigger: 'blur' }],
    rent: [
      { required: true, message: "请输入租金", trigger: "blur" },
      { pattern: /^(0|([1-9][0-9]*))?(.\d{1,2})?$/, message: "请输入正确的租金", trigger: ["blur", "change"] }
    ],
    area: [
      { required: true, message: "请输入面积", trigger: "blur" },
      { pattern: /^(0|([1-9][0-9]*))?(.\d{1,2})?$/, message: "请输入正确的面积", trigger: ["blur", "change"] }
    ],
    deposit: [
      { required: true, message: "请输入押金", trigger: "blur" },
      { pattern: /^(0|([1-9][0-9]*))?(.\d{1,2})?$/, message: "请输入正确的押金", trigger: ["blur", "change"] }
    ],
    people: [
      { required: true, message: "请输入居住人数", trigger: "blur" },
      { pattern: /^([1-9][0-9]*)$/, message: "请输入正确的居住人数", trigger: ["blur", "change"] }
    ],
  },
  cohabitants: {
    visible: false,
    type: 'add',
    form: {}
  },
  rentRange: {
    visible: false,
    type: 'add',
    form: {}
  },
  addBilling: {
    visible: false,
    type: 'add',
    form: {}
  },
  receivables: {
    visible: false,
    type: 'add',
    form: {}
  },
  remarkForm: {
    remark: undefined,
  },
  roomInfoForm: {
    roomInfo: undefined
  },
  otherForm: {
    other: undefined
  }
})
const { form, formRules, cohabitants, rentRange, addBilling, receivables, remarkForm, roomInfoForm, otherForm } = toRefs(data)

// 判断是否为闰年
function isLeapYear(year) {
  if (year % 4 === 0) {
      if (year % 100 === 0) {
          return year % 400 === 0;
      } else {
          return true
      }
  } else {
      return false
  }
}

// 快速选择周期
function handleQuicklyDate(number) {
  const startDate = new Date(form.value.checkInStart)
  let nextMonth = startDate.getMonth() + number
  let date = startDate.getDate()
  let nextDate = date
  let sMonth = nextMonth % 12
  let year = startDate.getFullYear() + (nextMonth / 12)
  if (sMonth === 1 && date > 28) {
    if (isLeapYear(year)) nextDate = date > 29 ? 29 : 28
    else nextDate = 28
  } else if ([3, 5, 8, 10].includes(sMonth) && date === 31) {
    nextDate = 30
  } else {
    nextDate = date - 1
  }
  form.value.checkInEnd = parseTime(new Date(year, sMonth, nextDate), '{y}-{m}-{d}')
}

function handleStartDateChange() {
  radio.value = ''
}
function handleEndDateChange() {
  radio.value = ''
}

/* 添加同住人 */
function handleCohabitants() {
  cohabitants.value.visible = true
}
function handleCohabitantsClose() {
  cohabitants.value.visible = false
}
function handleCohabitantsOk(params) {
  console.log(params);
  // 添加操作
  params.mainFlag = 0
  form.value.renterList.push(params)
  cohabitants.value.visible = false
}
// 删除同住人
function handleRemoveRenter(index) {
  form.value.renterList.splice(index, 1)
}

/* 添加房租信息 */
function handleRentRange() {
  console.log(rentRange.value.form);
  if (Object.values(rentRange.value.form).find(item => item !== undefined)) {
    rentRange.value.type = 'edit'
  } else {
    rentRange.value.type = 'add'
  }
  rentRange.value.form = form.value.rentObject
  rentRange.value.visible = true
}
function handleRentRangeClose() {
  rentRange.value.visible = false
}
function handleRentRangeOk(params) {
  form.value.rentObject = { ...params }
  rentRange.value.visible = false
}

/* 添加记账 */
function handleAddBilling() {
  addBilling.value.visible = true
}
function handleAddBillingClose() {
  addBilling.value.visible = false
}
function handleAddBillingOk(params) {
  const row = { ...params }
  row.type = 2
  row.noticeDate = params.payDate
  billList.value.push(row)
  addBilling.value.visible = false
}

/* 添加待收账单 */
function handleReceivables() {
  receivables.value.visible = true
}
function handleReceivablesClose() {
  receivables.value.visible = false
}
function handleReceivablesOk(rows) {
  for (const key in rows) {
    const params = { ...rows[key] }
    params.type = 1
    billList.value.push(params)
  }
  receivables.value.visible = false
}

/* 租金发生变化 */
function handleRentChange(value) {
  form.value.deposit = value
}

/* 合同预览 */
function handleContactsView() {
  console.log('合同预览');
}

/* 备注 */
function handleRemark() {
  remarkForm.value.remark = form.value.remark
  remarkVisible.value = true
}
function handleRemarkOk() {
  form.value.remark = remarkForm.value.remark
  remarkVisible.value = false
}
function handleRemarkCancel() {
  remarkForm.value.remark = undefined
  // proxy.resetForm('remarkFormRef')
  remarkVisible.value = false
}

/* 房间物品 */
function handleRoomInfo() {
  roomInfoForm.value.roomInfo = form.value.roomInfo
  roomInfoVisible.value = true
}
function handleRoomInfoOk() {
  form.value.roomInfo = roomInfoForm.value.roomInfo
  roomInfoVisible.value = false
}
function handleRoomInfoCancel() {
  proxy.resetForm('roomInfoFormRef')
  roomInfoVisible.value = false
}

/* 其他约定 */
function handleOther() {
  otherForm.value.other = form.value.other
  otherVisible.value = true
}
function handleOtherOk() {
  form.value.other = otherForm.value.other
  otherVisible.value = false
}
function handleOtherCancel() {
  proxy.resetForm('otherFormRef')
  otherVisible.value = false
}

// 完成提交
function handleFinish() {
  proxy.$refs['formRef'].validate(valid => {
    if (valid) {
      form.value.renterList[0].mainFlag = 1
      checkinApi.save(form.value).then(res => {
        successVisible.value = true
      })
      
    }
  })
}

/* 获取房间信息 */
function getRoomInfo() {
  if (!form.value.roomId || form.value.roomId === '') {
    return
  }
  RoomApi.getDetail(form.value.roomId).then(res => {
    roomInfo.value = res.data
  })
}

/* 成功事件点击事件 */
function handleSuccessOk() {
  router.back()
}
</script>
